<template>
  <a-form-model
    v-if="data"
    ref="ruleForm"
    :model="checkForm"
    :rules="checkRules"
    :label-col="{ span: 3 }"
    :wrapper-col="{ span: 11 }"
  >
    <a-alert
      v-if="[-1, 1].includes(status)"
      :message="status === -1 ? fail_reason : '正在审核中'"
      banner
      style="margin-bottom:20px;"
    />

    <div class="title">门店信息设置</div>
    <a-form-model-item label="店铺门头照" prop="out_door_images">
      <cyyUploadImg
        :disabled="disabled"
        @uploadSuccess="e => (checkForm.out_door_images = e.data)"
        @deleteImg="checkForm.out_door_images = ''"
        :imgSrc="checkForm.out_door_images"
      >
      </cyyUploadImg>
    </a-form-model-item>

    <a-form-model-item label="店铺名称" prop="shop_name">
      <a-input :disabled="disabled" placeholder="请输入店铺名称" v-model="checkForm.shop_name" />
    </a-form-model-item>

    <a-form-model-item label="经营类型" prop="shop_type">
      <a-radio-group v-model="checkForm.shop_type" :disabled="disabled">
        <a-radio value="01">直营</a-radio>
        <a-radio value="02">加盟</a-radio>
      </a-radio-group>
    </a-form-model-item>

    <a-form-model-item label="选择店铺类目" prop="shop_category">
      <a-cascader
        :disabled="disabled"
        :options="shop_cat"
        placeholder="请选择店铺类目"
        v-model="checkForm.shop_category"
      />
    </a-form-model-item>

    <a-form-model-item label="省市区/县" required>
      <a-cascader
        :disabled="disabled"
        :options="area_code"
        :fieldNames="{
          label: 'name',
          value: 'adcode',
          children: 'children'
        }"
        placeholder="请选择省市区/县"
        v-model="getAddressSelect"
      />
    </a-form-model-item>

    <a-form-model-item label="详细地址" prop="business_address.address">
      <a-input :disabled="disabled" placeholder="请输入详细地址" v-model="checkForm.business_address.address" />
    </a-form-model-item>

    <a-form-model-item label="经纬度坐标">
      <div style="display: flex;">
        <a-input style="flex:1;" disabled :value="getMarker" />
        <a-button v-if="!disabled" type="primary" @click="onClickSelectMap"> 搜索地图 </a-button>
      </div>
    </a-form-model-item>

    <a-form-model-item label="门店编号">
      <a-input disabled placeholder="请输入门店编号" v-model="checkForm.store_id" />
    </a-form-model-item>

    <a-form-model-item label="特殊资质证书类型">
      <a-select placeholder="请选择特殊资质证书类型" v-model="checkForm.qualifications.industry_qualification_type">
        <a-select-option :value="item.bussiness_code" v-for="item of QualificationType" :key="item.bussiness_code">{{
          item.bussiness_type
        }}</a-select-option>
      </a-select>
    </a-form-model-item>

    <a-form-model-item label="特殊资质证书图片">
      <cyyUploadImg
        :disabled="disabled"
        @uploadSuccess="e => (checkForm.qualifications.industry_qualification_image = e.data)"
        @deleteImg="checkForm.qualifications.industry_qualification_image = ''"
        :imgSrc="checkForm.qualifications.industry_qualification_image"
      >
      </cyyUploadImg>
    </a-form-model-item>

    <a-form-model-item :wrapper-col="{ span: 11, offset: 3 }">
      <a-button v-if="!disabled" v-loading="isLoading" class="btn" type="primary" @click="submit">提交审核</a-button>
      <a-button class="btn" @click="$router.go(-1)"> 返回 </a-button>
    </a-form-model-item>

    <SelectMap v-if="mapVisiable" :oldmarker="getMarker" :value.sync="mapVisiable" @onOk="selectMapOk"></SelectMap>
  </a-form-model>
</template>

<script>
import { createdShop, getShopBaseData } from '@/api/setting/applet'
import { cyyUploadImg } from '@/components/CyyUi/index'
import SelectMap from '@/components/SelectMap/SelectMap'
import { formatDataToTree } from '@/utils/utils'

export default {
  components: {
    cyyUploadImg,
    SelectMap
  },

  watch: {
    data: {
      handler(newVal) {
        if (newVal) {
          this.getData(newVal)
        }
      },
      immediate: true,
      deep: true
    }
  },

  props: {
    data: {
      type: Object,
      default() {
        return null
      }
    }
  },

  computed: {
    getMarker() {
      let { longitude, latitude } = this.checkForm.business_address

      if (longitude && latitude) {
        return `${longitude},${latitude}`
      }
      return ''
    },

    getAddressSelect: {
      get() {
        let { province_code, city_code, district_code } = this.checkForm.business_address
        return [province_code, city_code, district_code]
      },
      set(val) {
        let [province_code, city_code, district_code] = val
        this.checkForm.business_address.province_code = province_code
        this.checkForm.business_address.city_code = city_code
        this.checkForm.business_address.district_code = district_code
      }
    },

    getBindFace() {
      let str = ''
      if (this.data && this.data.batch_status) {
        console.log('batch_status,', this.data.batch_status)

        switch (parseInt(this.data.batch_status)) {
          case 3:
            str = '审核中'
            break

          case 4:
            str = '异常单'
            break

          case 7:
            str = '商户超时未确认'
            break

          case 8:
            str = '审核失败'
            break
        }
      }

      return str
    }
  },

  data() {
    return {
      fail_reason: '',
      status: 0,
      mapVisiable: false,
      area_code: [],
      QualificationType: [],
      isLoading: false,
      disabled: false,
      defaultValue: [],

      // 提交审核的小程序表单
      mini_id: undefined,
      checkForm: {
        business_address: {
          city_code: '',
          district_code: '',
          province_code: '',
          longitude: '',
          latitude: '',
          address: ''
        },
        store_id: '',
        shop_category: [],
        shop_name: '',
        shop_type: '01',
        qualifications: {
          industry_qualification_image: '',
          industry_qualification_type: ''
        },
        out_door_images: ''
      },

      // 提交审核验证规则
      checkRules: {
        out_door_images: [{ required: true, message: '请上传店铺门头照' }],
        shop_name: [{ required: true, message: '请输入店铺名称', trigger: 'blur' }],
        shop_type: [{ required: true, message: '请选择经营类型', trigger: 'change' }],
        shop_category: [{ required: true, message: '请选择店铺类目', trigger: 'change' }],
        'business_address.address': [{ required: true, message: '请输入详细地址', trigger: 'blur' }]
      }
    }
  },

  methods: {
    selectMapOk(e) {
      let [latitude,longitude] = e.split(',')
      this.checkForm.business_address.longitude = longitude
      this.checkForm.business_address.latitude = latitude
    },

    onClickSelectMap() {
      this.mapVisiable = true
    },

    async submit() {
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          this.isLoading = true

          let { mini_id, checkForm } = this,
            params_data = JSON.parse(JSON.stringify(checkForm))

          if (!params_data.id) {
            delete params_data.id
          }

          if (!params_data.business_address.province_code) {
            this.$message.error('请选择省市区')
            return
          }

          params_data.shop_category = params_data.shop_category[params_data.shop_category.length - 1]

          const hide = this.$message.loading('加载中', 0)

          const res = await createdShop({ mini_id, params_data: checkForm })
          this.isLoading = false
          if (res.code == 0) {
            this.$message.success('签约成功')
            this.$emit('changeData')
          } else {
            this.$message.error(res.msg)
          }
          hide()
        } else {
          return false
        }
      })
    },

    getNewShopCat(list) {
      let arr = [],
        obj = {}

      if (list.length) {
        for (let i = 0; i < list.length; i++) {
          if (obj[list[i].first_code]) {
            let { secode_cat: label, secode_code: value } = list[i]

            obj[list[i].first_code].children.push({
              value,
              label
            })

            continue
          }

          let { first_cat: label, first_code: value } = list[i]
          obj[list[i].first_code] = {
            value,
            label,
            children: []
          }
        }

        for (let i in obj) {
          arr.push(obj[i])
        }
      }

      return arr
    },

    getData({ id: mini_id }) {
      const hide = this.$message.loading('加载中', 0)
      getShopBaseData({
        mini_id
      }).then(res => {
        hide()
        if (!res.code) {
          let { QualificationType, area_code, shop_cat, info, mini_id } = res.data

          this.shop_cat = this.getNewShopCat(shop_cat)
          this.QualificationType = QualificationType
          this.area_code = area_code
          this.mini_id = mini_id

          if (info) {
            let {
              store_id,
              business_address,
              new_shop_category: shop_category,
              shop_name,
              qualifications,
              out_door_images,
              shop_type,
              id,
              status,
              fail_reason
            } = info

            let parent = shop_cat.find(el => el.secode_code === shop_category)

            this.checkForm = {
              business_address,
              shop_category: [parent ? parent.first_code : '', shop_category],
              shop_name,
              shop_type,
              store_id,
              qualifications,
              out_door_images,
              id
            }

            this.status = status
            this.fail_reason = fail_reason

            if ([1].includes(status)) {
              this.disabled = true
            }
          }

          return
        }

        this.$message.error(res.msg)
      })
    }
  }
}
</script>

<style lang="less" scoped>
.title {
  font-size: 16px;
  color: rgba(0, 0, 0, 0.85);
  margin-bottom: 14px;
}

.btn {
  margin: 0 5px;
}

.tip {
  margin-top: 10px;
  margin-bottom: 10px;
  font-size: 14px;
  color: rgba(0, 0, 0, 0.45);
  line-height: normal;
}

.hr {
  margin-bottom: 24px;
  height: 1px;
  background: #e8e8e8;
}
</style>
